<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Api\Controller;
use App\Handles\WechatHandle;
use App\Models\User;

class AuthorizationsController extends Controller
{
    /**
     * Update the specified user.
     *
     * @param  Request  $request
     * @return Response
     */
    public function qyWxLogin(Request $request, WechatHandle $wechatHandle)
    {
        //获取员工企业userid
        $qwUserInfo = $wechatHandle->qyWechat()->qyJscode2session($request->input('code'));
        if ($qwUserInfo['errcode'] != 0) {
            return $this->failed('登录失败');
        }
        //去请求数据库


        // $qwUserInfo['userid']='10528';
        // //去请求中台，拿到员工信息
        // $employeeDetail = $cloudHandle->setConfig($wechatHandle->organization->cloud_host,$wechatHandle->organization->ent_id)->getLoginEmployeeInfo($qwUserInfo['userid']);
        // //请求saas库，拿到该企业下的员工信息
        // $organizationDetail = $defaultModel->getOrganizationDetail($employeeDetail['corporateCode']);//主信息
        // //设置DB连接
        // $defaultModel->setMysqlStandardCustom($organizationDetail->DATABASEINFO);
        // //查询连接库的用户信息
        // $sUserDetail = $userService->getLoginEmpDetail($employeeDetail,$organizationDetail);

        // $userData = [
        //     'keyId'=> $employeeDetail['corporateCode']."-".$employeeDetail['employeeCode'],
        //     'data'=>[
        //         'endId'=>$employeeDetail['corporateCode'],
        //         'empCode'=>$employeeDetail['employeeCode'],
        //         'phone'=>$employeeDetail['phone'],
        //         'corpId'=>$qwUserInfo['corpid'],
        //         'orgGuid'=>$sUserDetail['ORGGUID'],
        //         'userGuid'=>$sUserDetail['GUID'],
        //     ]
        // ];
        // $token=auth('api')->login(User::make($userData));

        // if($token) {
        //     return $this->success(['token' => 'bearer ' . $token]);
        // }
        // return $this->failed('登录失败');
    }


    /**
     * 小程序登录
     * return $token
     */
    public function wxLogin(Request $request, WechatHandle $wechatHandle)
    {
        $code = $request->input('code');
        $userInfo = $wechatHandle->wxLogin($code);
        if (isset($userInfo['errcode']) && $userInfo['errcode'] != 0) {
            return $this->failed('获取用户openid,session_key,unionid信息失败~');
        }
        //获取信息成功存入session
        Redis::set('wechat:user:' . $userInfo['openid'], json_encode($userInfo));
        return $this->success(['s_token' => base64_encode($userInfo['openid'])]);
    }

    /**
     * 微信小程序获取电话
     */
    public function getMobile(Request $request, WechatHandle $wechatHandle)
    {
        $data = $request->post();
        $arr_userinfo = json_decode(Redis::get('wechat:user:' . base64_decode($data['s_token'])), true);
        $session_key = $arr_userinfo['session_key'];
        $decryptedData = $wechatHandle->decryptData($session_key, $data['iv'], $data['encryptedData']);
        $userData = User::where('CODE', $decryptedData['purePhoneNumber'])->first();

        if ($userData == false) {
            return $this->failed('登录失败!');
        }
        $token = auth('api')->login($userData);
        if ($token) {
            return $this->success(['token' => 'bearer ' . $token,'userPhone'=>$decryptedData['purePhoneNumber']]);
        }
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        try {
            $user = auth()->userOrFail();
            return $this->success($user);
        } catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) {
            // do something
            return $this->failed('sorry,token invalid');
        }
    }

    public function payload()
    {
        $payload = auth()->payload();
        
        return $this->success($payload);
        // then you can access the claims directly e.g.
        // $payload->get('sub'); // = 123
        // $payload['jti']; // = 'asfe4fq434asdf'
        // $payload('exp'); // = 123456
        // $payload->toArray(); // = ['sub' => 123, 'exp' => 123456, 'jti' => 'asfe4fq434asdf'] etc
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return $this->success('Successfully logged out');
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return $this->success([
            'access_token' => $token,
            'token_type' => 'bearer',
            // 'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }
}
